<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['product:attr:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['product:attr:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['product:attr:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['product:attr:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="attrList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="序号" align="center" prop="no" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['product:attr:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['product:attr:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改属性模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input clearable v-model="form.name" placeholder="请输入名称" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="序号" prop="no">
          <!-- <el-input v-model="form.no" placeholder="请输入序号" /> -->
          <el-input-number v-model="form.no" :min="1" :step="1"></el-input-number>
        </el-form-item>
        <el-divider content-position="center">属性值信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddProductAttrValue">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini"
              @click="handleDeleteProductAttrValue">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="productAttrValueList" :row-class-name="rowProductAttrValueIndex"
          @selection-change="handleProductAttrValueSelectionChange" ref="productAttrValue">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="编号" align="center" prop="index" width="50" />
          <el-table-column label="排序" prop="no" width="150">
            <template slot-scope="scope">
              <!-- <el-input v-model="scope.row.no" placeholder="请输入序号" /> -->
              <el-input-number v-model="scope.row.no" :min="1" :step="1" style="width:120px"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="属性名" prop="attrName" width="200">
            <template slot-scope="scope">
              <el-input v-model="scope.row.attrName" placeholder="请输入属性名" />
            </template>
          </el-table-column>
          <el-table-column label="属性值" prop="attrValue" width="400">
            <!-- <el-input v-model="scope.row.attrValue" placeholder="请输入属性值" /> -->
            <template slot-scope="scope">
              <el-tag :key="tag" v-for="tag in scope.row.attrValue" closable :disable-transitions="false"
                @close="handleClose(scope.row, tag)">
                {{ tag }}
              </el-tag>
              <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="inputValue"
                :ref="inputRefId(scope.row)" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)">
              </el-input>
              <el-button v-else class="button-new-tag" size="small"
                @click="showInput(scope.row, inputRefId(scope.row))">+ 标签</el-button>
            </template>
          </el-table-column>

        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAttr, getAttr, delAttr, addAttr, updateAttr } from "@/api/product/attr";

export default {
  name: "Attr",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedProductAttrValue: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 属性模板表格数据
      attrList: [],
      // 属性值表格数据
      productAttrValueList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "模板名称不能为空", trigger: "blur" }
        ],
        no: [
          { required: true, message: "序号不能为空", trigger: "blur" }
        ]
      },
      inputValue: '',
      // 用于存储生成的唯一 ID
      inputRefIds: {},
      nextId: 999999, // 初始的临时 ID
    };
  },
  created() {
    this.getList();
  },
  methods: {

    /** 查询属性模板列表 */
    getList() {
      this.loading = true;
      listAttr(this.queryParams).then(response => {
        this.attrList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        no: null
      };
      this.productAttrValueList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加属性模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAttr(id).then(response => {
        // 处理 productAttrValueList 中的 attValue
        response.data.productAttrValueList.forEach(item => {
          if (item.attrValue && item.attrValue.includes(',')) {
            // 如果 attValue 存在值且包含逗号，则将其分割成数组
            item.attrValue = item.attrValue.split(',').map(value => value.trim());
          } else {
            // 如果 attValue 不存在值或者不包含逗号，则将其视为一个包含单个元素的数组
            item.attrValue = item.attrValue ? [item.attrValue] : [];
          }

          // 为每个属性值对象添加 inputVisible 和 inputValue 字段
          item.inputVisible = false;
          item.inputValue = '';
        });
        this.form = response.data;
        this.productAttrValueList = response.data.productAttrValueList;
        this.open = true;
        this.title = "修改属性模板";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 处理 scProductAttValueList 中的 attValue，将数组转换为以逗号分隔的字符串数组
          let hasEmptyValue = false; // 是否存在空值的标志
          let nameEmptyValue = false; // 是否存在空值的标志
          let noEmptyValue = false; // 是否存在空值的标志

          this.productAttrValueList.forEach(item => {
            if (!item.attrValue || item.attrValue.length === 0) {
              // 如果 attValue 为空值或者为空数组，则将 hasEmptyValue 设置为 true
              hasEmptyValue = true;
              return; // 中断 forEach 循环
            }

            if (!Array.isArray(item.attrValue)) {
              // 如果 attValue 不是数组，则将其视为一个包含单个元素的数组
              item.attrValue = [item.attrValue]; // 将单个元素转换为数组
            }

            item.attrValue = item.attrValue.join(','); // 使用 join() 方法将数组转换为以逗号分隔的字符串

            if (item.id && typeof item.id === 'string' && item.id.includes('temp_')) {
              item.id = null;
            }

            if (!item.attrName) {
              nameEmptyValue = true;
            }

            if (!item.no || isNaN(item.no)) {
              noEmptyValue = true;
            }
          });

          // 如果存在空值，则给出提示并终止提交
          if (hasEmptyValue) {
            this.productAttrValueList.forEach(item => {
              // console.log(item)
              if (item.attrValue && item.attrValue.length > 0) {
                item.attrValue = item.attrValue.split(','); // 使用 join() 方法将数组转换为以逗号分隔的字符串
              }
            });
            this.$message.error('属性值不能为空！');
            return;
          }

          if (nameEmptyValue) {
            this.productAttrValueList.forEach(item => {
              if (item.attrValue && item.attrValue.length > 0) {
                item.attrValue = item.attrValue.split(','); // 使用 join() 方法将数组转换为以逗号分隔的字符串
              }
            });
            this.$message.error('属性名不能为空！');
            return;
          }

          if (noEmptyValue) {
            this.productAttrValueList.forEach(item => {
              if (item.attrValue && item.attrValue.length > 0) {
                item.attrValue = item.attrValue.split(','); // 使用 join() 方法将数组转换为以逗号分隔的字符串
              }
            });
            this.$message.error('编号不能为空或非数字！');
            return;
          }

          this.form.productAttrValueList = this.productAttrValueList;
          if (this.form.id != null) {
            updateAttr(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAttr(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(err => {
              // this.$modal.msgError("模板名称已存在");
              this.$alert('模板名称已存在，请更换模板名称', '添加失败', {
                confirmButtonText: '确定',
                callback: action => {
                  this.$message({
                    type: 'info',
                    message: `action: ${action}`
                  });
                }
              });
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除属性模板编号为"' + ids + '"的数据项？').then(function () {
        return delAttr(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 属性值序号 */
    rowProductAttrValueIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 属性值添加按钮操作 */
    handleAddProductAttrValue() {
      let obj = {};
      obj.id = 'temp_' + this.nextId;
      obj.attrName = "";
      obj.attrValue = "";
      obj.inputVisible = false;
      obj.no = "";
      this.productAttrValueList.push(obj);
    },
    /** 属性值删除按钮操作 */
    handleDeleteProductAttrValue() {
      if (this.checkedProductAttrValue.length == 0) {
        this.$modal.msgError("请先选择要删除的属性值数据");
      } else {
        const productAttrValueList = this.productAttrValueList;
        const checkedProductAttrValue = this.checkedProductAttrValue;
        this.productAttrValueList = productAttrValueList.filter(function (item) {
          return checkedProductAttrValue.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleProductAttrValueSelectionChange(selection) {
      this.checkedProductAttrValue = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('product/attr/export', {
        ...this.queryParams
      }, `attr_${new Date().getTime()}.xlsx`)
    },

    handleClose(row, tag) {
      if (!row.attrValue || row.attrValue.length === 0) {
        // 如果 attValue 为空，给出提示并终止函数执行
        this.$message.warning('标签为空，无法删除！');
        return;
      }

      row.attrValue.splice(row.attrValue.indexOf(tag), 1);
    },
    inputRefId(row) {
      // console.log("row", row)
      // 如果行没有 ID，则生成一个临时的唯一 ID
      if (!row.id) {
        if (!this.inputRefIds.hasOwnProperty(row)) {
          // 为行添加临时的唯一 ID
          const tempId = "temp_" + this.nextId;
          this.$set(this.inputRefIds, row, tempId);
          row.id = tempId; // 将临时 ID 保存在行对象中
          this.nextId++;
        }
        return this.inputRefIds[row];
      }
      // 否则，使用行的 ID 作为 ref
      return row.id;
    },
    handleInputConfirm(row) {
      const inputValue = this.$refs[row.id].$refs.input.value;

      // 判断 inputValue 是否包含逗号
      if (inputValue.includes(',') || inputValue.includes('，')) {
        // 如果包含逗号，提示用户并提前结束函数执行
        this.$modal.msgError("输入内容不能包含逗号");
        return;
      }

      // 如果 row.inputValue 不存在或不是数组，则将其初始化为空数组
      if (!Array.isArray(row.attrValue)) {
        row.attrValue = [];
      }

      if (inputValue) {
        row.attrValue.push(inputValue);
      }

      row.inputVisible = false;
      // 清空输入框的值
      this.inputValue = '';
    },
    showInput(row, id) {
      row.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs[id].$refs.input.focus();
      });
    },
  }
};
</script>
<style>
.el-tag+.el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>